/*
 * Copyright (c) 2008, Xiong Yingfei, the University of Tokyo
 * All rights reserved.
 */
package ac.jp.u_tokyo.SyncLib.dictionaries;

import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

import ac.jp.u_tokyo.SyncLib.Mod;
import ac.jp.u_tokyo.SyncLib.Value2Mod;

public class Map2DictMod extends Value2Mod
{

	@Override
	public <T> Mod<T> findModImpl(T source, T target)
	{
		assert target != null && !target.equals(source);
		
		Map<Object, Object> tmap = (Map) target;
		Map<Object, Object> smap;
		if (source == null) smap = new HashMap();
		else smap = (Map) source;

		DictModFactory<Object, Object> result = new DictModFactory<Object, Object>();
		
		Set<Object> keyInTarget = new HashSet(tmap.keySet());
		for (Map.Entry<Object, Object> sentry : smap.entrySet()) {
			Object tvalue = tmap.get(sentry.getKey());
			if (tvalue != null) {
				result.addPut(sentry.getKey(), 
						findMod(sentry.getValue(), tvalue));
			}
			else {
				result.addRemove(sentry.getKey());
			}
			keyInTarget.remove(sentry.getKey());
		}
		
		for (Object key : keyInTarget) {
			result.addPut(key, findMod(null, tmap.get(key)));
		}
		
		return (Mod<T>) result.create();
	}
	
	public final static Map2DictMod INSTANCE = new Map2DictMod();
	
}


